import { computed } from 'vue'

export type EmitEvent = (event: string, ...args: any[]) => void

export function useModel<Type>(props: Record<string, any>, propsName: string, emit: EmitEvent) {
  return computed<Type>({
    get() {
      // 如果值不是对象或为undefined，直接返回原始值
      const value = props[propsName]
      if (!value || typeof value !== 'object') {
        return value
      }

      // 只有当值是对象时才创建代理
      return new Proxy(value, {
        get(target, key, receiver) {
          return Reflect.get(target, key, receiver)
        },
        set(target, key, value) {
          emit(`update:${propsName}`, { ...target, [key]: value })
          return true
        },
      })
    },
    set(val) {
      emit(`update:${propsName}`, val)
    },
  })
}

export function useVModel<Type>(props: Record<string, any>, propsName: string, emit: EmitEvent) {
  return computed<Type>({
    get() {
      return props[propsName]
    },
    set(val) {
      emit(`update:${propsName}`, val)
    },
  })
}
